package net.kong.sns.rest.client.user;

import net.kong.sns.rest.client.method.JsonMethodInvokeBase;
import net.kong.sns.rest.client.model.UserInfo;
import net.kong.sns.rest.client.model.UserInfoImpl;
import net.kong.sns.rest.client.KongApiMethod;
import net.kong.sns.rest.client.InvalidResponseException;
import net.kong.sns.rest.client.rest.HttpResponseContent;
import net.kong.org.springframework.util.StringUtils;

import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.Map;
import java.util.List;

/**
 * @author <a href="mailto:lanhuai@gmail.com">Ning Yubin</a>
 * @version $Id: UsersStandardInfoInvoke.java,v 1.2 2009/11/04 17:17:38 ningyubin Exp $
 */
public class UsersStandardInfoInvoke extends JsonMethodInvokeBase<Set<UserInfo>> {
    public UsersStandardInfoInvoke(Long[] userIds) {
        super(KongApiMethod.USERS_GET_STANDARD_INFO, "");
        setParameter("user_ids", StringUtils.arrayToCommaDelimitedString(userIds));
        setParameter("fields", StringUtils.arrayToCommaDelimitedString(UserInfo.Field.values()));
    }

    public UsersStandardInfoInvoke(Long[] userIds, UserInfo.Field[] fields) {
        super(KongApiMethod.USERS_GET_STANDARD_INFO, "");
        setParameter("user_ids", StringUtils.arrayToCommaDelimitedString(userIds));
        setParameter("fields", StringUtils.arrayToCommaDelimitedString(fields));
    }

    @Override
    protected Set<UserInfo> processJsonResponse(HttpResponseContent responseData) throws InvalidResponseException {
        String response = responseData.getBody();
        Object o = reader.read(response);
        Set<String> initializedFields = new HashSet<String>();
        Set<UserInfo> set = new HashSet<UserInfo>();
        String fields = getParameter("fields");
        if (fields != null) {
            initializedFields.addAll(Arrays.asList(fields.split(",")));
        }
        List<Map<String, Object>> userList = (List<Map<String, Object>>) o;
        for (Map<String, Object> map : userList) {
            UserInfoImpl userInfo = new UserInfoImpl();
            userInfo.initialize(map, initializedFields);
            set.add(userInfo);
        }
        return set;
    }
}
